package com.garen.spring.web.client;

import com.garen.core.Span;
import com.garen.spring.web.client.event.WebCollectEvent;
import com.google.common.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * ClassName: CollectorServer
 * Description: 收集器端Server
 *
 * @author kang.wang03
 *         Date 16/9/8
 */
public class CollectorServer {
    private static EventBus eventBus;
    private ScheduledExecutorService executorService;
    private ConcurrentLinkedQueue<Span> spanLinkedList = new ConcurrentLinkedQueue();

    static {
        eventBus = new EventBus();
    }

    public CollectorServer() {
        eventBus.register(this);
        executorService = Executors.newScheduledThreadPool(1);
        executorService.schedule(new Runnable() {
            @Override
            public void run() {
                int length = spanLinkedList.size();
                if (length > 10) {
                    for (int i = 0; i < length; i++) {
                        List<Span> spanList = new ArrayList<Span>();
                        spanList.add(spanLinkedList.remove());
                    }
                }
            }
        }, 3000, TimeUnit.SECONDS);
    }

    public static void publishEvent(Object event) {
        eventBus.post(event);
    }

    public void onWebUrlEvent(WebCollectEvent webCollectEvent) {
        if (webCollectEvent.span != null) {
            spanLinkedList.add(webCollectEvent.span);
        }
    }

}
